<?php

namespace App\Extensions;

use App\Extensions\Grid\Displayers\DropdownActions;
use App\Extensions\Grid\Displayers\Actions;
use Encore\Admin\Grid;
use App\Extensions\Grid\EColumn as Column;
use Encore\Admin\Grid\Exporter;
use Illuminate\Support\Str;

class EGrid extends Grid
{
    /**
     * Add a column to Grid.
     *
     * @param string $name
     * @param string $label
     *
     * @return Column|Grid\Column
     */
    public function column($name, $label = ''): Column
    {
        if (Str::contains($name, '.')) {
            return $this->addRelationColumn($name, $label);
        }

        if (Str::contains($name, '->')) {
            return $this->addJsonColumn($name, $label);
        }
        return $this->__call($name, array_filter([$label]));
    }

    /**
     * Add column to grid.
     *
     * @param string $column
     * @param string $label
     *
     * @return Column
     */

    protected function addColumn($column = '', $label = ''): Column
    {
        $column = new Column($column, $label);
        $column->setGrid($this);

        return tap($column, function ($value) {
            $this->columns->push($value);
        });
    }

    public function prependColumn($column = '', $label = '')
    {
        $column = new Column($column, $label);
        $column->setGrid($this);

        return tap($column, function ($value) {
            $this->columns->prepend($value);
        });
    }

    public function setCustomActionsClass(): EGrid
    {
        $this->setActionClass(Actions::class);
        return $this;
    }

    public function setCustomDropdownActionsClass(): EGrid
    {
        $this->setActionClass(DropdownActions::class);
        return $this;
    }

    public function render()
    {
        if (request(Exporter::$queryName)) {
            if (config('admin.caching_grid_selector')) {
                cache_grid_column($this);
            }
        }
        return parent::render(); // TODO: Change the autogenerated stub
    }


}
